package com.ciccwm.auth.config;

import com.ciccwm.auth.service.RedisDegradeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * 定时任务配置.
 */
@Slf4j
@Configuration
@EnableScheduling
@RequiredArgsConstructor
public class ScheduleConfig {
    private static final int SCHEDULE_POOL_SIZE = 10;
    private static final int FIXED_DELAY_MS = 300000;

    private final RedisDegradeService redisDegradeService;

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(SCHEDULE_POOL_SIZE);
        scheduler.setThreadNamePrefix("scheduled-task-");
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setAwaitTerminationSeconds(60);
        return scheduler;
    }

    @Scheduled(fixedDelay = FIXED_DELAY_MS)
    public void syncLocalCacheToRedis() {
        log.info("Starting to sync local cache to Redis");
        try {
            redisDegradeService.syncLocalCacheToRedis();
            log.info("Successfully synced local cache to Redis");
        } catch (Exception e) {
            log.error("Failed to sync local cache to Redis", e);
        }
    }
} 
